package com.zrh.jsd.service.studydemo.threadpool;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class CallAbleTest {
    // 使用了future，
    // 但因为调用了，get方法获取返回值，并没有实现真正的异步调用
    // 如果不调用get方法，是可以异步执行的
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int n = 10;
        Callable<Integer> mycallabletask = new MyCallableTask("aaaa");
        FutureTask<Integer> futuretask = new FutureTask<Integer>(mycallabletask);
        new Thread(futuretask).start();
//        System.out.println("1111" + n + futuretask.get());

        Callable<Integer> mycallabletask1 = new MyCallableTask1();
        FutureTask<Integer> futuretask1 = new FutureTask<Integer>(mycallabletask1);
        new Thread(futuretask1).start();
//        System.out.println("2222" + n + futuretask1.get());

        Callable<Integer> mycallabletask2 = new MyCallableTask2();
        FutureTask<Integer> futuretask2 = new FutureTask<Integer>(mycallabletask2);
        new Thread(futuretask2).start();
//        System.out.println("3333" + n + futuretask2.get());

        System.out.println(n + futuretask.get() + futuretask1.get() + +futuretask2.get());
    }
}

//定义实现Callable接口的的实现类重写call方法。
class MyCallableTask implements Callable<Integer> { //传参
    private String name;

    public MyCallableTask(String name) {
        this.name = name;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println("name==============" + name);
        System.out.println("call 方法开始执行===" + new Date());
        TimeUnit.SECONDS.sleep(10);
        System.out.println("call 执行结束返回===" + new Date());
        return 10;
    }
}

//定义实现Callable接口的的实现类重写call方法。
class MyCallableTask1 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("call1 方法开始执行===" + new Date());
        TimeUnit.SECONDS.sleep(20);
        System.out.println("call1 执行结束返回===" + new Date());
        return 10;
    }
}

//定义实现Callable接口的的实现类重写call方法。
class MyCallableTask2 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("call2 方法开始执行===" + new Date());
        TimeUnit.SECONDS.sleep(5);
        System.out.println("call2 执行结束返回===" + new Date());
        return 10;
    }
}